package gui;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class ManyEars extends Frame {
	private Button button = new Button("ManyEars");
	private TextArea textArea = new TextArea(40, 40);

	public ManyEars(String title) {
		super(title);

		for (int i = 0; i < 5; i++) {
			button.addActionListener(new ListenerA());
			print(i + "ListenerA is added.");
		}
		button.addMouseListener(new ListenerB());
		textArea.addKeyListener(new KeyHandler());
		add(button, BorderLayout.NORTH);
		add(textArea, BorderLayout.CENTER);
		pack();
		setVisible(true);
	}

	private void print(String str) {
		textArea.setText(textArea.getText() + str + "\n");
	}

	private static int count;

	class ListenerA implements ActionListener {
		private int num;

		public ListenerA() {
			count++;
			num = count;
		}

		public void actionPerformed(ActionEvent e) {
			print("ListenerA " + num + " receives ActionEvent.");
		}
	}

	class KeyHandler implements KeyListener {

		@Override
		public void keyPressed(KeyEvent e) {
			// TODO Auto-generated method stub
			print("keyPressed");
		}

		@Override
		public void keyReleased(KeyEvent e) {
			// TODO Auto-generated method stub
			print("keyReleased");
		}

		@Override
		public void keyTyped(KeyEvent e) {
			// TODO Auto-generated method stub
			print("keyTyped");
		}

	}

	class ListenerB extends MouseAdapter {
		public void mousePressed(MouseEvent e) {
			ActionListener[] listeners = (ActionListener[]) button
					.getListeners(ActionListener.class);
			print("ListenerB receives MouseEvent.");
			if (listeners.length > 0) {
				button.removeActionListener(listeners[0]);
				print("LA is removed.");
			}
			print("there are "
					+ (listeners.length > 0 ? listeners.length - 1 : 0)
					+ " ListenerA");
			MouseListener[] mls = button.getMouseListeners();
			button.removeMouseListener(mls[0]);
		}

	}

	public static void main(String[] args) {
		new ManyEars("listener test");
	}
}
